package com.ruoyi.rsikManage.task;

import com.ruoyi.rsikManage.domain.AlarmEvent;
import com.ruoyi.rsikManage.domain.AlarmSendingUrlConfig;
import com.ruoyi.rsikManage.service.ITAlarmsService;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletContext;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.ruoyi.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;

@Component
@Getter
@Setter
public class AlgoAlarmSendingScheduler implements SchedulingConfigurer {
    @Autowired
    ITAlarmsService alarmsService;
    @Value("${scheduler.alarmSendingCron}")
    private String initialAlarmSendingCron;
    private boolean isLastReceiveCornErr;
    @Value("${scheduler.alarmSendingCron}")
    private String alarmSendingCron;
    @Autowired
    ServletContext servletContext;
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> {
            sendAlarmInfo();
        }, triggerContext -> {
            CronTrigger cronTrigger;
            if (isLastReceiveCornErr) {
                cronTrigger = new CronTrigger(initialAlarmSendingCron);
            }else {
                try {
                    cronTrigger = new CronTrigger(alarmSendingCron);
                }catch (IllegalArgumentException e) {
                    System.out.println("上次接收的alarmSendingCron:\""+ alarmSendingCron + "\" 格式错误，alarmSendingCron 更新为初始值======");
                    cronTrigger = new CronTrigger(initialAlarmSendingCron);
                    isLastReceiveCornErr = true;
                }
            }
            return cronTrigger.nextExecutionTime(triggerContext);
        });
    }

    public void sendAlarmInfo() {
        System.out.println("执行报警信息的检查与发送任务========" + LocalDateTime.now().format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS)));
        //1.查询未发送的报警信息
        AlarmEvent alarmParam = new AlarmEvent();
        alarmParam.setAlarmSendingMark(0);
        List<AlarmEvent> AlarmListOfNotSent =  alarmsService.selectAlarmEventList(alarmParam);
        List<AlarmSendingUrlConfig>  AlarmSendingUrlConfigList = (List<AlarmSendingUrlConfig>) servletContext.getAttribute("urlListWhereTheAlarmInfoIsSent");
        //2.发送未发送的报警信息
        if (AlarmListOfNotSent != null && AlarmListOfNotSent.size() > 0 && AlarmSendingUrlConfigList != null) {
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity httpEntity = new HttpEntity(AlarmListOfNotSent);
            for (AlarmSendingUrlConfig alarmSendingUrlConfig : AlarmSendingUrlConfigList) {
                ResponseEntity<String> exchange = restTemplate.exchange(alarmSendingUrlConfig.getUrl(), HttpMethod.POST, httpEntity, String.class);
            }
        }
        //3.将发送报警信息标记未已发送
        if (AlarmListOfNotSent != null && AlarmListOfNotSent.size() > 0) {
            alarmsService.markAlarmEventAsSent(AlarmListOfNotSent);
        }
    }
}
